package com.jlu.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlu.yygh.listener.DictListener;
import com.jlu.yygh.mapper.DictMapper;
import com.jlu.yygh.model.cmn.Dict;
import com.jlu.yygh.service.DictService;
import com.jlu.yygh.vo.cmn.DictEeVo;
import com.sun.deploy.net.URLEncoder;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

//    导入 allEntries = true: 方法调用后清空所有缓存
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile multipartFile) {
        try {
            EasyExcel.read(multipartFile.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportData(HttpServletResponse response) throws Exception{
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //Dict ->DictEeVo
        List<Dict> dictList = dictMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        for(Dict dict : dictList) {
            DictEeVo dictVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictVo, DictEeVo.class);
            dictVoList.add(dictVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }
    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count>0;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

//        先根据dictcode查出dict，再根据dict的id查出下级节点
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);

        List<Dict> chlidData = this.findChlidData(dict.getId());

        return chlidData;
    }

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public String getNameByParentDictCodeAndValue(String dictCode,String value) {

////        如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
//        if(StringUtils.isEmpty(parentDictCode)){
//
//            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//
//            wrapper.eq("value",value);
//            Dict dict = baseMapper.selectOne(wrapper);
//
//            return dict.getName();
//        }else {
//
////            先根据dict_code查出字典对象，再查出字典对象的parent_id，再根据这个parent_id和value查出字典
//            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//            wrapper.eq("dict_code",value);
//            Dict dictCode = baseMapper.selectOne(wrapper);
//
////            获取字典对象的parent_id
//            Long parentId = dictCode.getId();
//
//            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>()
//                    .eq("parent_id",parentId)
//                    .eq("value", value));
//
//            return dict.getName();
//
//        }
        //如果dictCode为空，直接根据value查询
        System.out.println("付清" + dictCode);
        System.out.println("erzi" + value);
        if (value.equals("CertificatesType")){
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",10);
            wrapper.eq("parent_id", 20000);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }
        if(StringUtils.isEmpty(dictCode)) {
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {//如果dictCode不为空，根据dictCode和value查询
            //根据dictcode查询dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            //根据parent_id和value进行查询
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

}
